/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.dspl.validate.validator;

import com.google.dspl.model.Concept;
import com.google.dspl.model.Dataset;
import com.google.dspl.model.Slice;
import com.google.dspl.model.Table;
import com.google.dspl.model.Topic;
import com.google.dspl.validate.ItemReference;
import com.google.dspl.validate.ValidationContext;
import com.google.dspl.validate.violation.Violation;

import java.util.List;

/**
 * {@link Validator} that checks that ids in the global top-level namespace are unique
 * (topic, concept, slice and table ids).
 *
 * @author Maryla Ustarroz Calonge
 */
public class GlobalUniqueIdValidator implements Validator<Dataset> {

  @Override
  public List<Violation> validate(Dataset dataset, ValidationContext context) {
    UniqueIdViolationAccumulator uniqueIdValidator = new UniqueIdViolationAccumulator();

    validateTopicIds(dataset, dataset.getTopics(), uniqueIdValidator);

    for (Concept concept : dataset.getConcepts()) {
      ItemReference itemReference = ItemReference.reference(dataset, concept);
      uniqueIdValidator.addId(concept.getId(), itemReference);
    }

    for (Slice slice : dataset.getSlices()) {
      ItemReference itemReference = ItemReference.reference(dataset, slice);
      uniqueIdValidator.addId(slice.getId(), itemReference);
    }

    for (Table table : dataset.getTables()) {
      ItemReference itemReference = ItemReference.reference(dataset, table);
      uniqueIdValidator.addId(table.getId(), itemReference);
    }

    return uniqueIdValidator.getViolations();
  }

  private void validateTopicIds(
      Dataset dataset, List<Topic> topics, UniqueIdViolationAccumulator uniqueIdValidator) {
    for (Topic topic : topics) {
      ItemReference itemReference = ItemReference.reference(dataset, topic);
      uniqueIdValidator.addId(topic.getId(), itemReference);

      validateTopicIds(dataset, topic.getChildTopics(), uniqueIdValidator);
    }
  }
}
